// frontend/src/store/db.ts

import { openDB } from 'idb'
import type { DBSchema, IDBPDatabase } from 'idb'

/** 数据库结构定义（兼容所有核心数据） */
interface WidgetDB extends DBSchema {
  widgets: {
    key: string; // 唯一ID
    value: {
      id: string
      type: string
      config: any
      position: { x: number; y: number }
      size: { w: number; h: number }
      status: string // 启用、禁用等
      group?: string
    }
  }
  plugins: {
    key: string
    value: {
      id: string
      name: string
      version: string
      enabled: boolean
      author?: string
      entry: string
      apiVersion: string
      manifest?: any
    }
  }
  userPrefs: {
    key: string
    value: any
  }
  backup: {
    key: string
    value: {
      timestamp: number
      widgets: any[]
      plugins: any[]
      userPrefs: any
      note?: string
    }
  }
}

let dbPromise: Promise<IDBPDatabase<WidgetDB>>

/** 初始化数据库实例 */
export function getDB() {
  if (!dbPromise) {
    dbPromise = openDB<WidgetDB>('widget-platform', 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains('widgets')) db.createObjectStore('widgets', { keyPath: 'id' })
        if (!db.objectStoreNames.contains('plugins')) db.createObjectStore('plugins', { keyPath: 'id' })
        if (!db.objectStoreNames.contains('userPrefs')) db.createObjectStore('userPrefs')
        if (!db.objectStoreNames.contains('backup')) db.createObjectStore('backup', { keyPath: 'timestamp' })
      }
    })
  }
  return dbPromise
}

/** 通用CRUD封装 */

export async function saveData<T extends keyof WidgetDB>(store: T, record: WidgetDB[T]['value']) {
  const db = await getDB()
  // @ts-ignore
  await db.put(store, record)
}

export async function loadData<T extends keyof WidgetDB>(store: T, key?: string) {
  const db = await getDB()
  if (key) {
    // @ts-ignore
    return await db.get(store, key)
  }
  // @ts-ignore
  return await db.getAll(store)
}

export async function deleteData<T extends keyof WidgetDB>(store: T, key: string) {
  const db = await getDB()
  // @ts-ignore
  await db.delete(store, key)
}

/** 快照备份 */
export async function makeSnapshot(note = '') {
  const db = await getDB()
  const widgets = await db.getAll('widgets')
  const plugins = await db.getAll('plugins')
  const userPrefs = await db.getAll('userPrefs')
  const timestamp = Date.now()
  await db.put('backup', { timestamp, widgets, plugins, userPrefs, note })
}

/** 恢复指定快照 */
export async function restoreSnapshot(timestamp: number) {
  const db = await getDB()
  // 这里用 as any 避免类型冲突，实际运行无影响
  const backup = await db.get('backup', timestamp as any)
  if (!backup) throw new Error('未找到快照')
  for (const table of ['widgets', 'plugins', 'userPrefs'] as const) {
    // @ts-ignore
    await db.clear(table)
    // @ts-ignore
    for (const item of backup[table]) await db.put(table, item)
  }
}


